﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace APNS.NET
{

    // Represents a device token, this uniquly identifieds a device to send a notification to
    public class DeviceToken
    {

        private byte[] _deviceToken;

        public static implicit operator DeviceToken(string deviceToken)
        {
            return new DeviceToken() { _deviceToken = DeviceTokenStringToBytes(deviceToken) };
        }  

        public static DeviceToken FromBytes(byte[] bytes, int startIndex)
        {
            if (bytes == null) 
                throw new ArgumentNullException("bytes");

            var result = new DeviceToken();
            result._deviceToken = new byte[bytes.Length - startIndex];
            Array.Copy(bytes, startIndex, result._deviceToken, 0, bytes.Length-startIndex);

            return result;
        }

        private static byte[] DeviceTokenStringToBytes(string token)
        {
            if (token == null) 
                throw new ArgumentNullException("token");

            var result = new byte[token.Length / 2];
            for (int i = 0; i < result.Length; i++)
                result[i] = byte.Parse(token.Substring(i * 2, 2), NumberStyles.HexNumber);

            return result;
        }

        public byte[] ToByteArray()
        {            
            return _deviceToken;
        }

    }
}
